package com.xxl.job.common.utils.i18n;

import com.xxl.job.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 获取i18n资源文件
 *
 * @author admin
 */
public class MessageUtils {
    //@Autowired
    //private static final HttpServletRequest request =
    //        ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }

    /**
     * 根据消息键 获取消息 委托给spring messageSource(通过 Request请求的语言来决定国际化)
     *
     * @param messageKey 消息键
     * @return 获取国际化翻译值
     */
    public static String getMessage(String messageKey) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        String message = messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale());
        return message;
    }
}
